﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Baosight.ZNH.ZMCommon;
using Baosight.Platform.Core;
using Baosight.ZNH.ZMCM.UI.ChildWindows;
using Baosight.ZNH.ZMCommon.ChildWindows;
using Telerik.Windows.Controls;
using Baosight.Platform.Core.ServiceModel;
using Baosight.Platform.Core.UI.Controls;
using Baosight.ZNH.ZMCM.UI.Utils;
using System.Windows.Browser;
using System.Text;
using Telerik.Windows.Controls.GridView;

namespace Baosight.ZNH.ZMCM.UI
{
    public partial class ZMCMD6 : EFViewCmes
    {
        IServiceAgent service;
        private EIInfo tempEIInfo;
        private EIBlock measurBlock;
        private EIBlock empBlock;
        private EIBlock orgBlock;

        private object Str  //得到当前记录生效状态
        {
            get { return this.grid.SelectedItem.GetType().GetProperty("fdStatus").GetValue(this.grid.SelectedItem, null); }
        }

        public ZMCMD6()
        {
            InitializeComponent();
            service = new HttpServiceAgent();
        }
        public override void Initialize(EIInfo initData)
        {
            initData.AddBlock((new StockBlock()).GetStatusBlock());
            base.Initialize(initData);
            measurBlock = initData.GetBlock("cmes.cs.units");
            empBlock = initData.GetBlock("cmes.cm.empName");
            orgBlock = initData.GetBlock("cmes.cm.department");
         }
        /// <summary>
        /// 主表选中记录发生改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangeEventArgs e)
        {
            if (null != this.grid.SelectedItem)
            {
                //根据状态判断从表的按钮是否可用
                BtnVisibilityByStatus();

                EIInfo info = new EIInfo();
                info.Attributes.Add(EIConstants.ServiceNameKey, "ZMCMD7");
                info.Attributes.Add(EIConstants.MethodNameKey, "query");

                EIRow _row = (this.grid.SelectedItem as UIBaseEntity).GetEIRow();
                info.Attributes.Add("fdStockPlanId", _row["fdKeyId"].ToString());
                info.Attributes.Add("fdYear", _row["fdYear"].ToString());
                info.Attributes.Add("fdMonth", _row["fdMonth"].ToString());

                EIBlock block = new EIBlock("params");
                block.AddRow((this.grid.SelectedItem as UIBaseEntity).GetEIRow());
                info.AddBlock(block);

                info.AddBlock(EIConstants.ResultBlock).Set(EIConstants.ShowCount, "true");
                service.CallService(info, OnCallChildServiceCompleted);
                
            }
            else
            {
                EIInfo info = new EIInfo();
                info.AddBlock("Planresult");
                this.ChildGrid.UpdateData(info);
            }
        }
        /// <summary>
        /// 刷新从表数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnCallChildServiceCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            tempEIInfo = e.EIInfo;//更新缓存
            this.ChildGrid.UpdateData(e.EIInfo);
        }

        /// <summary>
        /// 根据状态判断从表的按钮是否可用
        /// </summary>
        private void BtnVisibilityByStatus()
        {
            if (Str.Equals("0"))
            {
                Button insert = this.FindName("PLANINSERT") as Button;
                if (insert != null)
                {
                    insert.IsEnabled = true;
                }
                Button update = this.FindName("PLANUPDATE") as Button;
                if (update != null)
                {
                    update.IsEnabled = true;
                }
                Button delete = this.FindName("PLANDELETE") as Button;
                if (delete != null)
                {
                    delete.IsEnabled = true;
                }
            }
            else
            {
                Button insert = this.FindName("PLANINSERT") as Button;
                if (insert != null)
                {
                    insert.IsEnabled = false;
                }
                Button update = this.FindName("PLANUPDATE") as Button;
                if (update != null)
                {
                    update.IsEnabled = false;
                }
                Button delete = this.FindName("PLANDELETE") as Button;
                if (delete != null)
                {
                    delete.IsEnabled = false;
                }
            }
        }

        #region 主表操作

        /// <summary>
        /// 主表新增操作/编制计划
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnInsertButtonClick(object sender, RoutedEventArgs e)
        {
            base.TempButton = sender as Button;
            base.TempButton.IsEnabled = false;
            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCMD8");
            eiInfo.Set("method", "query");
            eiInfo.Set("fdParentId", this.fdParentId.Value);

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, OnDoWorkCompleted);
          //  base.OnInsertButtonClickPopup(eiInfo, "需求计划", "insert", "Parent", sender, e);
        }

        private void OnDoWorkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status != -1)
            {
                base.OnInsertButtonClickPopup(e.EIInfo, "编制需求计划", "insert", "Parent", this.TempButton, null);
            }
            else
            {
                base.OpenEFWindowAlert("有错误！", true);
            }
        }
        /// <summary>
        /// 主表删除操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnDeleteButtonClick(object sender, RoutedEventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.EFGridCheckedRows = this.grid.GetCheckedEIRows();
            base.ViewProperty = null;
            base.ViewProperty = _view;             //不能使用OnBeforeAction方法，在这里赋值
            base.OnDeleteButtonClick(sender, e);
        }
        /// <summary>
        /// 主表生效操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnReportButtonClick(object sender, RoutedEventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.EFGridCheckedRows = this.grid.GetCheckedEIRows();
            base.ViewProperty = null;
            base.ViewProperty = _view;             //不能使用OnBeforeAction方法，在这里赋值

            base.OnModifyButtonClick("report", "生效", sender, e);
        }

        /// <summary>
        /// 主表打印操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnPrintButtonClick(object sender, RoutedEventArgs e)
        {
            //按钮失效
            Button _button = sender as Button;
            _button.IsEnabled = false;
            base.TempButton = _button;
            StringBuilder fdKeyId = new StringBuilder();
            int count = this.grid.GetCheckedEIRows().Count;
            if (count <= 0)
            {
                this.OpenEFWindowAlert("请选择记录进行打印！", true);
                return;
            }
            else
            {

                for (int i = 0; i < count; i++)
                {
                    if (i == count - 1)
                    {
                        fdKeyId.Append("'" + this.grid.GetCheckedEIRows()[i]["fdKeyId"].ToString() + "'");
                        break;
                    }
                    fdKeyId.Append("'" + this.grid.GetCheckedEIRows()[i]["fdKeyId"].ToString() + "',"); ;
                }
            }
            Uri uri = Uploader.ConstructAbsoluteUri("../admin/RunmaxReport.jsp?projectName=CMESReport&reportName=StockMoth&KeyId=" + fdKeyId);
            HtmlPage.Window.Navigate(uri, "_blank");
            base.TempButtonOpen(true);//按钮生效
        }
        /// <summary>
        /// 主表弹出窗口关闭时执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ParentInsertWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == true)
            {
                //刷新Grid区域
                this.grid.Refresh();
            }

            //按钮生效
            base.TempButtonOpen(true);
        }

        /// <summary>
        /// 在删除和生效时进行校验，已生效的不能删除和生效
        /// </summary>
        /// <param name="_eIRows"></param>
        /// <returns></returns>
        public override bool BeforeMethod(List<EIRow> _eIRows)
        {
            foreach (EIRow row in _eIRows)
            {
                
                if (row["fdStatus"] !=null && row["fdStatus"].Equals("1"))
                {
                    BaseTools.OpenEFWindowAlert("勾选的记录包含已生效记录，不能" + TempButton.Content + "，请重新选择!", null);
                    this.TempButtonOpen(true);
                    return false;
                }
            }
            return true;
        }
      

        #endregion
        #region 从表操作

        /// <summary>
        /// 从表新增操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnPlanInsertButtonClick(object sender, RoutedEventArgs e)
        {

            EIRow _row = this.grid.EIBlock.GetRow(this.grid.SelectedIndex);
            if (null == _row)
            {
                //按钮失效
                Button _button = sender as Button;
                _button.IsEnabled = false;
                base.TempButton = _button;
                base.OpenEFWindowAlert("请先选择一条或者录入一条记录！",true);
                return;
            }
            else
            {

                EIInfo eiInfo = new EIInfo();
                base.OnInsertButtonClickPopup(eiInfo, "月计划明细-新增", "insert", "Child", sender, e);
              
            }
        }
        /// <summary>
        /// 从表修改操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnPlanUpdateButtonClick(object sender, RoutedEventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.EFGridCheckedRows = this.ChildGrid.GetCheckedEIRows();
            base.ViewProperty = null;
            base.ViewProperty = _view;                       //不能使用OnBeforeAction方法，在这里赋值

            IList<EIRow> _list = this.ChildGrid.GetCheckedEIRows() == null ? new List<EIRow>() : this.ChildGrid.GetCheckedEIRows();

            EIInfo eiInfo = new EIInfo();
            EIBlock eIBlock = new EIBlock("result");
            EIRow row = new EIRow();
            if (_list.Count > 0)
            {
                row = BaseTools.GetEIRowByOldEIRow(this.EIDataContext.GetBlock("Planresult").GetColumns(), _list[0]);
            }
            eIBlock.SetRow(0, row);
            eiInfo.AddBlock(eIBlock);
            base.OnUpdateButtonClickPopup(eiInfo, "月计划明细-修改", "update", "Child", sender, e);
        }
        /// <summary>
        /// 从表删除事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnPlanDeleteButtonClick(object sender, RoutedEventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.EFGridCheckedRows = this.ChildGrid.GetCheckedEIRows();
            base.ViewProperty = null;
            base.ViewProperty = _view;              //不能使用OnBeforeAction方法，在这里赋值

            base.OnDeleteButtonClick("ZMCMD7", "delete", sender, e);
        }
        /// <summary>
        /// 从表弹出窗口关闭时执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ChildInsertWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == true)
            {
                //刷新从表Grid区域
                this.ChildGrid.Refresh();
                this.grid.Refresh();// 刷新从表时刷新主表
            }

            //按钮生效
            base.TempButtonOpen(true);
        }
       
        #endregion

        #region 公共方法
        /// <summary>
        /// 包括主表、从表
        /// 新增、修改、查看之前的数据传输
        /// 构造新增页面内容、弹出页面
        /// </summary>
        /// <param name="eIInfo"></param>
        /// <param name="title"></param>
        public override void OpenPopup(EIInfo _eIInfo, string _title, string _dialogType, string _args)
        {
            _eIInfo.AddBlock(this.EIDataContext.GetBlock("cmes.cs.units"));
            if (_args.ToLower() == "parent")
            {
                this.ParentOpenPopup(_eIInfo, _title, _dialogType);
            }
            else
            {
                this.ChildOpenPopup(_eIInfo, _title, _dialogType);
            }
        }
        /// <summary>
        /// 主表新增或修改之前的数据传输
        /// 构造新增页面内容、弹出页面
        /// </summary>
        /// <param name="eIInfo"></param>
        /// <param name="title"></param>
        private void ParentOpenPopup(EIInfo _eIInfo, string _title, string _dialogType)
        {
            NeedPlanforMonthWindow needPlanforMonth = new NeedPlanforMonthWindow(_dialogType);//构造一个新的弹出页面
            needPlanforMonth.EIDataContext = new Platform.Core.UI.EIDataContext();
            _eIInfo.AddBlock(empBlock);
            _eIInfo.AddBlock(orgBlock);
            needPlanforMonth.EIDataContext.Update(_eIInfo);

            needPlanforMonth.fdParentId.Value = this.fdParentId.Value;//当前节点ID
            needPlanforMonth.fdParentName.Value = this.fdParentName.Value;//当前节点名称
            needPlanforMonth.isLeaf.Value = this.isLeaf.Value;//是否叶子

            needPlanforMonth.UpdatePlan += new EventHandler<EventArgs>(needplan_UpdatePlan);//更新主表

            CmesWindows _popup = new CmesWindows();//构造一个弹出页面
            _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
            _popup.Header = _title == null ? "" : _title;//设置Title
            _popup.Content = needPlanforMonth;//让新增页面在弹出窗口显示
            _popup.Closed += new EventHandler<WindowClosedEventArgs>(ParentInsertWindow_Closed);
            _popup.ShowDialog();//模态显示弹出窗口

        }
        void needplan_UpdatePlan(object sender, EventArgs e)
        {
            this.grid.Refresh();
        }

        /// <summary>
        /// 从表新增或修改之前的数据传输
        /// 构造新增页面内容、弹出页面
        /// </summary>
        /// <param name="eIInfo"></param>
        /// <param name="title"></param>
        private void ChildOpenPopup(EIInfo _eIInfo, string _title, string _dialogType)
        {
            NeedforYearDetailWindow zmcm59 = new NeedforYearDetailWindow(_dialogType);//构造一个新的修改页面
            zmcm59.EIDataContext = new Platform.Core.UI.EIDataContext();

            _eIInfo.AddBlock((new MaterialTypeBlock()).GetMaterialType());
            _eIInfo.AddBlock(measurBlock);                //添加计量单位下拉框block 
            zmcm59.EIDataContext.Update(_eIInfo);
            if (_dialogType == "insert")
            {
                EIRow _row = this.grid.EIBlock.GetRow(this.grid.SelectedIndex);
                zmcm59.fdStockPlanId.Value = _row["fdKeyId"];//主表ID
                zmcm59.fdYear.Value = _row["fdYear"];//主表年份
                zmcm59.fdMonth.Value = _row["fdMonth"];//主表月份
                ((zmcm59.fdMaterialCode.Content) as CmesCustomView).eViewInitParams = "bindingService=ZMCMD2.queryforCustomview,columns=fdKeyId|fdMaterialCode|fdMaterialName|fdQuality|fdSpecModel|fdNumber|fdStockNum|fdSafeBaseNum|fdPrice,queryConditions=fdMaterialCode|fdMaterialName|fdSpecModel,initParam=fdYear:" + _row["fdYear"].ToString() + "|fdMonth:" + _row["fdMonth"].ToString();
            }
            else
            {
                if (_eIInfo.GetBlock("result").Get(0, "fdRequirePlan") == null || 
                    !_eIInfo.GetBlock("result").Get(0, "fdRequirePlan").Equals("na"))
                {
                    zmcm59.fdNeedNum.IsReadOnly = true;
                }
            }

            CmesWindows _popup = new CmesWindows();//构造一个弹出页面
            _popup.MinHeight = 200;
            _popup.MinWidth = 300;
            _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
            _popup.Header = _title == null ? "" : _title;//设置Title
            _popup.Content = zmcm59;//让新增页面在弹出窗口显示
            _popup.Closed += new EventHandler<WindowClosedEventArgs>(ChildInsertWindow_Closed);
            _popup.ShowDialog();//模态显示弹出窗口
        }

     
        /// <summary>
        /// 执行删除后的页面操作
        /// 包括主表删除和从表删除
        /// </summary>
        public override void DoDeleteOperationCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            base.DoDeleteOperationCompleted(sender, e);
            if (this.grid.SelectedIndex == -1 || this.grid.SelectedItem == null)
            {
                EIInfo info = new EIInfo();
                info.AddBlock("Planresult");
                this.ChildGrid.UpdateData(info);
            }
            this.grid.Refresh();
        }

        #endregion

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton link = sender as HyperlinkButton;
            EIRow row = (link.ParentOfType<GridViewRow>().Item as UIBaseEntity).GetEIRow();
            string fdMaterialId = row["fdMaterialId"].ToString();
            string fdMaterialName = row["fdMaterialName"].ToString();
            string fdStockPlanId = row["fdStockPlanId"].ToString();

            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCMD7");
            eiInfo.Set("method", "queryApplicationDepartment");
            eiInfo.Set("fdMaterialId", fdMaterialId);
            eiInfo.Set("fdMaterialName", fdMaterialName);
            eiInfo.Set("fdStockPlanId", fdStockPlanId);

            EIBlock eIBlock = new EIBlock("result");
            eIBlock.SetRow(0, row == null ? new EIRow() : row);
            eiInfo.AddBlock(eIBlock);

            base.Submit(eiInfo, DoOperationCompleted);
        }

        public void DoOperationCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo inInfo = e.EIInfo;
            if (inInfo.Status == -1)
            {
                string _msg = inInfo.GetMsg();
                this.OpenEFWindowAlert(_msg, true);//列表中删除，操作失败后按钮生效
                return;
            }

            OpenDetailPopup(e.EIInfo, "申请单位-查看", "detail", null);
        }

        /// <summary>
        /// 新增或修改之前的数据传输
        /// 构造新增页面内容、弹出页面
        /// </summary>
        /// <param name="eIInfo"></param>
        /// <param name="title"></param>
        public void OpenDetailPopup(EIInfo _eIInfo, string _title, string _dialogType, string _args)
        {
            DepartmentDetail view = new DepartmentDetail();//构造一个新的修改页面
            view.EIDataContext = new Platform.Core.UI.EIDataContext();
            view.EIDataContext.Update(_eIInfo);

            EFWindow _popup = new EFWindow();//构造一个弹出页面  
            _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
            _popup.Header = _title == null ? "" : _title;//设置Title
            _popup.Content = view;//让新增页面在弹出窗口显示
            _popup.Closed += new EventHandler<WindowClosedEventArgs>(DetailWindow_Closed);
            _popup.ShowDialog();//模态显示弹出窗口
        }

        /// <summary>
        /// 弹出窗口关闭时执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DetailWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            //超链接生效
            if (base.TempHyperlink != null)
            {
                base.TempHyperlink.IsEnabled = true;
                base.TempHyperlink = null;
            }
        }
    }
}
